// 输入一个链表,输出该链表中倒数第k个节点

class Head0521 {
  constructor(public val: any = undefined, public next?: Head0521) { }
}

function getkthFromEnd(head: Head0521, k: number) {
  let length = 0
  let node: Head0521 | undefined = head
  while (node) {
    ++length
    node = node.next
  }
  if (k > length) {
    return null
  }
  node = head
  let offset = length - k
  for (let i = 0; i < offset; ++i) {
    node = node?.next
  }
  return node
}

function kmzz(head: Head0521, k: number) {
  let right: Head0521 | undefined = head
  for (let i = 0; i < k; ++i) {
    if (right == null) {
      return null
    }
    right = right.next
  }
  let left: Head0521 | undefined = head
  while (right) {
    left = left?.next
    right = right.next
  }
  return left
}

let head = new Head0521()
let v = 20
let m = null
while (v) {
  if (m) {
    m.next = new Head0521(v)
    m = m.next
  } else {
    head.next = new Head0521(v)
    m = head.next
  }
  v--
}

console.log(head)

